# ---- 
# Appendix table S6 and S7
# ---- 
load_library = c('bit64','data.table','fst','future.apply','stringr','logger','vroom')
invisible(lapply(load_library, function(x) library(x, character.only=TRUE, quietly= TRUE)))

library(parallel)
library(tidyverse)
library(ggalluvial)
library(ggsci)
library(hrbrthemes)
library(ggalt)

round_up = function(x, scale=100, digit=2) as.character(round(x * scale, digit))

bucket = '/Users/bk/Dropbox/project/OP/- posted/2021-06-08_covid_substitution_JAMA/dataverse'

dt = readLines(file.path(bucket, 'data','processed_data','mean_transition_period.txt'))

# read results
matrix_name = grep('\\t', dt, value=TRUE, invert=TRUE)
dt = grep('\\t', dt, value=TRUE, invert=FALSE)
dt = fread(text=dt)
dt = dt[V1 != '', ]
dt[, outcome := rep(matrix_name, each = 9)]
dt[, V5 := NULL]
names(dt) = c('stat', 'period1', 'period2', 'period3', 'outcome') 

dt = melt(dt, id.var=c('stat', 'outcome'))
dt[,value := as.numeric(value)]
dt[, period := stringr::str_extract(variable, '\\d{1}')]

dt[, c('dv1','dv2','state_t0','state_t1','year') := tstrsplit(outcome, '_')]

all_out_main = dcast(dt[stat %in% c('b', 'se', 't', 'pvalue', 'll', 'ul'), ], 
	year + period + state_t0 + state_t1 ~ stat, value.var = c('value'))

all_out_main[, data := factor(period, levels=c(1,2,3), labels=c('prepandemic','pandemic','latepandemic'))]

# line graphs overtime 
all_out_main[, condition_t0 := factor(state_t0, levels = c(0,1,2,3),
	labels=paste0('t0: ',c('no treatment','opioid only','therapy only','both')))]
all_out_main[, condition_t1 := factor(state_t1, levels = c(0,1,2,3),
	labels=paste0('t1: ',c('no treatment','opioid only','therapy only','both')))]

all_out_main[, print_cell := paste0(round_up(b), ' [', round_up(ll), ', ', round_up(ul), ']')]

df2019_pandemic = dcast(all_out_main[year==2019 & data == 'pandemic',], condition_t0~condition_t1, value.var='print_cell')
df2020_pandemic = dcast(all_out_main[year==2020 & data == 'pandemic',], condition_t0~condition_t1, value.var='print_cell')
df2019_prepandemic = dcast(all_out_main[year==2019 & data == 'prepandemic',], condition_t0~condition_t1, value.var='print_cell')
df2020_prepandemic = dcast(all_out_main[year==2020 & data == 'prepandemic',], condition_t0~condition_t1, value.var='print_cell')

write.csv(df2019_pandemic, 
	file.path(bucket, 'projects','covid_opioid','table_s6_transition_mat_2019_pandemic.csv'))
write.csv(df2019_prepandemic, 
	file.path(bucket, 'projects','covid_opioid','table_s6_transition_mat_2019_prepandemic.csv'))

write.csv(df2020_pandemic, 
	file.path(bucket, 'projects','covid_opioid','table_s7_transition_mat_2020_pandemic.csv'))
write.csv(df2020_prepandemic, 
	file.path(bucket, 'projects','covid_opioid','table_s7_transition_mat_2020_prepandemic.csv'))

